use std::sync::{Arc, RwLock};
use std::thread;

fn main() {
    //创建一个共享的变量整数，使用RwLock包装
    let counter = Arc::new(RwLock::new(0));
    //创建一个多线程读取计数器
    let mut read_handles = vec![];

    for _ in 0..3 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            //获取读取锁
            let num = counter.read().unwrap();
            println!("Reader {:?}: {}", thread::current().id(), *num);
        });
        read_handles.push(handle);
    }
    //创建一个线程来写入计算器的值
    let write_handle = thread::spawn(move || {
        //获取写入锁
        let mut num = counter.write().unwrap();
        *num += 1;
        println!(
            "Writer {:?}: Incremented counter to {}",
            thread::current().id(),
            *num
        );
    });

    //等待所有线程执行完成
    for handle in read_handles {
        handle.join().unwrap();
    }
    //等待写入线程完成
    write_handle.join().unwrap();
}
